<?php
declare (strict_types = 1);

namespace app\admin\controller\v1;

use app\admin\model\AdminLog;
use app\common\Backend;
use app\common\library\Upload;
use Qiniu\Auth;
use Qiniu\Storage\DownloadManager;
use think\facade\Config;
use think\Request;
use Throwable;

class Image extends Backend
{

    protected  $noNeedPermission = ['*'];

    public function initialize(): void
    {
        parent::initialize();
    }

    public function uploadImg(){
        AdminLog::setTitle(('upload'));
        if($this->request->has('class')){
          $obj = json_decode($this->request->param('class'),true);
          if(array_key_exists('class',$obj)){
                $class = $obj['class'];
            }else{
                $class = 'other';
            }
        }else{
            $class = 'other';
        }
        $file = $this->request->file('file');
        try {
            $upload     = new Upload($file);
            $attachment = $upload->upload(null,$class, $this->auth->id);
            unset($attachment['create_time'], $attachment['quote']);
        } catch (Throwable $e) {
            $this->error($e->getMessage());
        }
        $this->success(('File uploaded successfully'), [
            'file' => $attachment ?? []
        ]);
    }

    public function uploadSign()
    {
        // 用于签名的公钥和私钥
        $accessKey = Config::get('general.accessKey');
        $secretKey =  Config::get('general.secretKey');
        $auth = new Auth($accessKey, $secretKey);
        $bucket = Config::get('general.bucket');
        $token = $auth->uploadToken($bucket);
        $host = 'sl8hodub1.hd-bkt.clouddn.com';
        $uploadUrl = Config::get('general.upload_url');
        return $this->success('',['token'=>$token,'host'=>$host,'uploadUrl'=>$uploadUrl,'buket'=>$bucket]);
    }
}
